<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        :before-open="beforeOpen"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel">
        <template slot="menuLeft">
          <el-button
            v-if="permissions.pfoc_deviceparameterconfig_export"
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportExcel">导出
          </el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button v-if="scope.row.collectMode ==='数据平台'" type="text"  icon="el-icon-upload2"  size="small" plain  @click="upParameter(scope.row,'up')">上行参数</el-button>
          <el-button v-if="scope.row.collectMode ==='数据平台'"  type="text"  icon="el-icon-download"  size="small" plain  @click="downParameter(scope.row,'down')">下行参数</el-button>
          <el-button type="text"  icon="el-icon-edit"  size="small" plain  @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text"  icon="el-icon-delete"  size="small" plain  @click="handleDel(scope.row,scope.index)">删除</el-button>
        </template>
      </avue-crud>

      <!--参数弹窗页面-->
      <el-dialog :title="parameterTitle"
                 :visible.sync="parameterDialogVisible"
                 width="50%"
                 lock-scroll
                 v-dialogDrag
                 v-if="parameterDialogVisible"
                 :fullscreen="parameterDialogFull">
        <el-backtop target=".el-card__body .el-dialog__wrapper .el-dialog" :right="15" :bottom="20" :visibility-height="1" />
        <el-backtop :bottom="60"></el-backtop>
       <template slot="title">
          <div class="avue-crud__dialog__header">
            <span class="el-dialog__title">
                {{parameterTitle}}【
                <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
               设备名称：{{deviceName}}<i class="el-breadcrumb__separator el-icon-arrow-right"></i>设备编码：{{deviceSn}}
              】
            </span>
          </div>
        </template>
        <!--上行参数页面-->
        <upParameter ref="upParameterRef" v-if="parameterFlg==='up'" :deviceParameterId="id" :deviceSn="deviceSn" :deviceName="deviceName" />
        <!--下行参数页面-->
        <downParameter ref="downParameterRef"  v-if="parameterFlg==='down'"  :deviceParameterId="id" :deviceSn="deviceSn" :deviceName="deviceName"  />
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, addObj, putObj, delObj } from '@/api/pfoc/deviceparameterconfig'
// import { tableOption } from '@/const/crud/pfoc/deviceparameterconfig'
import { getDevice} from '@/api/hengdong/pfocinterface'//获取设备相关
import { getObj} from '@/api/pfoc/factorysettings' //获取当前工厂信息
import { mapGetters } from 'vuex'
import upParameter from "@/views/pfoc/deviceupparameter/index.vue";
import downParameter from "@/views/pfoc/devicedownparameter/index.vue";

export default {
  name: 'deviceparameterconfig',
  components: {
    upParameter,//上行参数页面
    downParameter//下行参数页面
  },
  data() {
    return {
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      deviceName:null,//设备名称
      deviceSn:null,//设备编码
      parameterTitle:null,//参数弹窗标题
      id:null,//参数配置表ID
      parameterFlg:undefined,//上下行参数页面标记
      parameterDialogVisible:false,//参数弹窗开关
      parameterDialogFull:true,//参数弹窗弹窗缩放开关（默认放大）
      tableLoading: false,
      tableOption:  {
        labelPosition: "right",
        labelSuffix: "：",
        labelWidth: 120,
        gutter: 0,
        menuBtn: true,
        align: "center",
        submitBtn: true,
        submitText: "提交",
        stripe: true,
        emptyBtn: true,
        emptyText: "清空",
        menuPosition: "center",
        border: true,
        index: true,
        indexLabel: "序号",
        searchMenuSpan:6,
        editBtn:false,
        delBtn:false,
        menuWidth:160,
        column: [
          {
            type: "select",
            label: "设备",
            prop: "device",
            span: 12,
            order:3,
            dicData:[],
            props: {
              label: "device",
              value: "device"
            },
            change:({column,value})=>{
              var t = this;
              t.deviceList.forEach(function (item, index) {
                if(value == item.device){
                  t.$set(t.$refs['crud'].tableForm, 'deviceSn', item.deviceSn);
                  t.$set(t.$refs['crud'].tableForm, 'deviceName', item.deviceName);
                }
              });
            },
            filterable:true,
            submit:false,
            display:true,
            hide:true,
            showColumn:false,
            rules: [
              {
                required: true,
                message: "设备不能为空"
              }
            ],

          },
          {
            type: "input",
            label: "设备编码",
            prop: "deviceSn",
            span: 12,
            order:1,
            disabled:true
          },
          {
            type: "input",
            label: "设备名称",
            prop: "deviceName",
            span: 12,
            order:1,
            disabled:true
          },
          {
            type: "select",
            label: "采集方式",
            prop: "collectMode",
            span: 12,
            order:2,
            dicData: [{
              label: '数据平台',
              value: "数据平台"
            }, {
              label: '自定义',
              value: "自定义"
            }],
            rules: [
              {
                required: true,
                message: "请选择采集方式"
              }
            ],
          },
          {
            type: "textarea",
            label: "备注",
            prop: "remarks",
            span: 12
          },
          {
            type: "input",
            label: "创建人",
            prop: "createBy",
            span: 12,
            dicUrl: "/admin/user/getAllUser",
            props: {
              label: "name",
              value: "username"
            },
            dicMethod: "get",
            display: false,
            hide: false
          },
          {
            type: "input",
            label: "创建时间",
            prop: "createTime",
            span: 12,
            width:90,
            format: "yyyy-MM-dd HH:mm:ss",
            display: false,
            hide: false,
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          },
          {
            type: "input",
            label: "修改人",
            prop: "updateBy",
            span: 12,
            dicUrl: "/admin/user/getAllUser",
            props: {
              label: "name",
              value: "username"
            },
            dicMethod: "get",
            display: false,
            hide: false
          },
          {
            type: "input",
            label: "更新时间",
            prop: "updateTime",
            span: 12,
            width:90,
            format: "yyyy-MM-dd HH:mm:ss",
            display: false,
            hide: false,
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          }
        ]
      },

    }
  },
  computed: {
    ...mapGetters(['permissions']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.pfoc_deviceparameterconfig_add, false),
        delBtn: this.vaildData(this.permissions.pfoc_deviceparameterconfig_del, false),
        editBtn: this.vaildData(this.permissions.pfoc_deviceparameterconfig_edit, false)
      }
    }
  },
  created() {
    //获取当前工厂信息
    this.getFactoryInfo();
  },
  methods: {
    // 列表查询
    getList(page, params) {
      this.tableLoading = true
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        this.page.total = response.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    //表单打开之前清空重置
    beforeOpen(done,type){
      if (["add"].includes(type)) {
        this.$nextTick(() => {
          var form =  this.$refs['crud'].tableForm;
          Object.keys(form).forEach((key) =>{
            form[key] = null;
          })
        })
      }
      done();
    },
    //默认编辑方法
    handleEdit:function(row,index){
      row.device =  row.deviceName +"——"+row.deviceSn;
      this.$refs.crud.rowEdit(row, index);
    },
    // 删除
    handleDel: function(row, index) {
      this.$confirm('是否确认删除ID为' + row.id, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList(this.page)
      })
    },
    // 更新
    handleUpdate: function(row, index, done, loading) {
      putObj(row).then(data => {
        this.$message.success('修改成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 保存
    handleSave: function(row, done, loading) {
      addObj(row).then(data => {
        this.$message.success('添加成功')
        done()
        this.getList(this.page)
      }).catch(() => {
        loading()
      })
    },
    // 每页条数改变事件
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    // 当前页发生改变事件
    currentChange(current) {
      this.page.currentPage = current
    },
    // 查询事件
    searchChange(form, done) {
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    // 刷新事件
    refreshChange() {
      this.getList(this.page)
    },
    //  导出excel
    exportExcel() {
      this.downBlobFile('/pfoc/deviceparameterconfig/export', this.searchForm, 'deviceparameterconfig.xlsx')
    },
    /**获取工厂信息*/
    getFactoryInfo() {
      const factoryId=1;
      getObj(factoryId).then(response => {
        this.organizationId = response.data.data.menuId;//组织ID
        this.organizationName = response.data.data.organizationName;//组织名称
        //获取工厂设备集合
        this.getFactoryDeviceList();
      })
    },
    /**获取工厂设备集合*/
    getFactoryDeviceList(){
      var obj={
        position:this.organizationName,//设置组织查询条件
      }
      getDevice(obj).then(response => {
        this.deviceList = response.data.data;//设备集合
        this.deviceList.forEach(data=>{
          data.device = data.deviceName +"——"+data.deviceSn;
        })
        var column = this.findObject(this.tableOption.column, 'device');
        column.dicData =  this.deviceList;
      } )
    },
    //打开上行参数页面
    upParameter(row,flg){
      this.parameterFlg = flg;
      this.parameterTitle="上行参数设置"
      this.parameterDialogVisible=true;//参数弹窗开关
      this.deviceSn=row.deviceSn;//设备编码
      this.deviceName=row.deviceName;//设备名称
      this.id = row.id;//参数配置表ID
      this.$nextTick(() => {
        //调用上行参数配置查询方法
        this.$refs.upParameterRef.refreshChange();
      })
    },
    //打开下行参数页面
    downParameter(row,flg){
      this.parameterFlg = flg;
      this.parameterTitle="下行参数设置"
      this.parameterDialogVisible=true;//参数弹窗开关
      this.deviceSn=row.deviceSn;//设备编码
      this.deviceName=row.deviceName;//设备名称
      this.id = row.id;//参数配置表ID
      this.$nextTick(() => {
        //调用下行参数配置查询方法
        this.$refs.upParameterRef.refreshChange();
      })
    },

  }
}
</script>
